const express =require("express")
const handleDB=require('./db/handleDB')
const multer=require('multer')
const fs=require('fs');
const path=require('path');
const qiniu= require('qiniu')
const localfile= require('./db/local/localfile')

const upload=multer({dest:'public/news/upload/'})//上传图片接口


const app=express();



//设置跨域请求头  一个中间件设置跨域  主要是Access-Control-Allow-Origin字段 允许的访问源
app.all('*', function (req, res, next) {    
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.get('/login',(req,res)=>{  
    (async function(){
       let {username,password}=req.query
       if(!username||!password){
           res.json({errmsg:'缺少必传参数'})
           return
       }
    //校验密码是否正确
       let result=await handleDB(res,"user","find","数据库查询出错",`username="${username}"`);    
       if(password!=result[0].password){
           
           res.send({errmsg:'用户名或密码不正确,登陆失败'})
           return
       }
       //保持用户登录状态
    //    req.session["user_id"]=result[0].id 
    //    console.log(req.session["user_id"]);
       //返回登录成功给前端
       let time1=Date.now()+parseInt(Math.random()*999)+parseInt(Math.random()*2222);
       let token='cbzuiyou'+time1
       res.send({code:"200",errmsg:"登陆成功",data:{result,token}})
    })();
})
//获取用户数据
app.get('/get_user',(req,res)=>{ 
  (async function(){
       let user_id=req.query.id; 
       let userlist = await handleDB(res,"user","find","数据库查询出错",`id="${user_id}"`)
       
       let sql2="SELECT count(*) as fans FROM `fans` WHERE follered_id ="+user_id
       let result2=await handleDB(res,"news","sql","数据库查询出错",sql2)
       let fans=result2[0].fans

       let sql3="SELECT count(*) as attention FROM `fans` WHERE ` foller_id`="+user_id
       let result3=await handleDB(res,"news","sql","数据库查询出错",sql3)
       let attention=result3[0].attention

       let sql4="SELECT count(*) as huozan FROM `news_like` WHERE user_id = "+user_id
       let result4=await handleDB(res,"news","sql","数据库查询出错",sql4)
       let huozan=result4[0].huozan

      let result={
        userlist,
        fans,
        attention,
        huozan
      }
      // console.log(result);
       res.send({code:"200",err:"successs",data:result})
    })();
})

//获取用户列表
app.get('/userList',(req,res)=>{
  (async function(){
  let result = await handleDB(res,"user","find","数据库查询出错")
  res.send({code:"200",err:"successs",data:result})
 })();
}) 

//用户聊天接口1
app.get('/chat',(req,res)=>{
  (async function(){
  let user_id=req.query.id; 
  // console.log(user_id);
  let sql="SELECT * FROM `message` LEFT JOIN user on message.user_id=user.id WHERE fri_id="+user_id
  let result = await handleDB(res,"user","sql","数据库查询出错",sql)
  res.send({code:"200",err:"successs",data:result})
 })();
})

//用户发送聊天接口
app.get('/send_chat',(req,res)=>{
  (async function(){
    // console.log(req.query);
    let {message,types,user_id,fri_id}=req.query
    let result = await handleDB(res,"message","insert","数据库查询出错",
    {
        message,
        types,
        user_id,
        fri_id
    })

   res.send({code:"200",err:"successs"})

   })();
})
 

//获取图片数据,实现下拉刷新
app.get('/news_picture',(req,res)=>{
        (async function(){
            let {page,rows,type_id}=req.query
            //查询每个用户发布的数据
            let sql1="SELECT news.*,user.name,user.icon FROM news LEFT JOIN user on news.user_id=user.id where type_id= "+type_id+" limit "+page+rows
            let result1 = await handleDB(res,"news","sql","数据库查询出错",sql1)

            //查询数据的总条数
            let sql2="SELECT COUNT(*) as totals FROM news WHERE type_id="+type_id
            let result2=await handleDB(res,"news","sql","数据库查询出错",sql2)
            let totals=result2[0]
            let data={pictureList:result1,}
            res.send({
                code:"200",
                err:"successs",
                data,
                totals,              
            })
         })();
})

//查询每条数据的评论数和点赞数
app.get('/likeAndComments',(req,res)=>{
  (async function(){
    let news_ids=req.query.news_id
    var list=[]
    for(var news_id of news_ids ){
        //查询每条数据的评论数
    let sql1="SELECT COUNT(*)  as comments FROM `comment` WHERE news_id ="+news_id
    let result1=await handleDB(res,"news","sql","数据库查询出错",sql1)
    let comments=result1[0].comments
   
    //查询每条数据的点赞数
    let sql2="SELECT COUNT(*)  as news_likes FROM news_like WHERE news_id ="+news_id
    let result2=await handleDB(res,"news","sql","数据库查询出错",sql2)
    let news_likes=result2[0].news_likes
     
    var data={comments,news_likes}
    // console.log(data);
    list.push(data)
  }
  res.send({code:"200",err:"successs",list})
 })();
})  

//获取数据详情
app.get('/news_detail',(req,res)=>{
    (async function(){
    let news_id=req.query.id; 
    let sql="SELECT * FROM `comment`  LEFT JOIN `user` on `comment`.user_id=user.id WHERE news_id = "+news_id
    let result = await handleDB(res,"news","sql","数据库查询出错",sql)

    let sql1="SELECT * FROM `news`  LEFT JOIN `user` on news.user_id=user.id WHERE news.id ="+news_id
    let result1 = await handleDB(res,"news","sql","数据库查询出错",sql1)
    res.send({code:"200",err:"successs",data:{result,result1}})
   })();
})  

// 评论功能
app.get('/comments',(req,res)=>{
    (async function(){
    let {content,user_id}=req.query
    let sql="insert into `comment`(user_id,news_id,content,create_time) VALUES ("+user_id+",1,'"+content+"','05-12')"
    let result = await handleDB(res,"news","sql","数据库查询出错",sql)
    res.send({code:"200",err:"successs",data:result})
   })();
})  
 //关注功能
 app.get('/Guan',(req,res)=>{ 
  (async function(){
     let {follered_id,foller_id}=req.query
    //  console.log(follered_id,foller_id);
    let sql="insert into fans (` foller_id`,follered_id) VALUES ("+foller_id+","+follered_id+")"
    let result = await handleDB(res,"news","sql","数据库查询出错",sql)

    res.send({code:"200",err:"successs",data:result})

    })();
})




//获取文字数据
app.get('/news_article',(req,res)=>{
    (async function(){
    let sql="SELECT news.*,user.name,user.icon FROM news LEFT JOIN user on news.user_id=user.id where type_id=2"
    let result = await handleDB(res,"news","sql","数据库查询出错",sql)
    res.send({code:"200",err:"successs",data:result})
   })();
})  

//获取视频数据
app.get('/news_video',(req,res)=>{
    (async function(){
        let sql="SELECT news.*,user.name,user.icon FROM news LEFT JOIN user on news.user_id=user.id where type_id=3"
        let result = await handleDB(res,"news","sql","数据库查询出错",sql)
        res.send({code:"200",err:"successs",data:result})
       })();  
})


//获取分类
app.get('/found_type',(req,res)=>{ 
    (async function(){
         let result = await handleDB(res,"found_type","find","数据库查询出错")
         res.send({code:"200",err:"successs",data:result})
      })();
  })


//获取分类数据详情
app.get('/found_detail',(req,res)=>{ 
    (async function(){
        let found_id=req.query.id
        let sql="SELECT news.*, found_type.found_name,found_type.found_img FROM news LEFT JOIN found_type on news.found_id=found_type.id  where found_id="+found_id
        let result = await handleDB(res,"news","sql","数据库查询出错",sql)

        res.send({code:"200",err:"successs",data:result})
      })();
  })

// 添加news接口
app.get('/addNews',(req,res)=>{ 
    (async function(){

       let {title,type,images,user_id}=req.query
       let result = await handleDB(res,"news","insert","数据库查询出错",
       {
           title:title,
           type_id:type,
           picture:images,
           user_id:user_id
       })

      res.send({code:"200",err:"successs",data:result})

      })();
  })

  //编辑资料接口
  app.get('/update_user',(req,res)=>{ 
    (async function(){
        // console.log(req.query);
        let {name,sex,icon,sign,user_id}=req.query
        let result = await handleDB(res,"user","update","数据库查询出错",`id="${user_id}"`,{
          name,
          sex,
          icon,
          sign
        })
        res.send({code:"200",err:"successs"})
      })();
  })

  //获取每个用户发布帖子
  app.get('/user_news',(req,res)=>{
    (async function(){
        let {page,rows,type_id,user_id}=req.query
        // 查询每个用户发布的数据
        let sql1="SELECT news.*,user.name,user.icon FROM news LEFT JOIN user on news.user_id=user.id where user.id="+user_id+" limit "+page+rows
        let result1 = await handleDB(res,"news","sql","数据库查询出错",sql1)

        //查询数据的总条数
        let sql2="SELECT COUNT(*) as totals FROM news WHERE type_id="+type_id
        let result2=await handleDB(res,"news","sql","数据库查询出错",sql2)
        let totals=result2[0]
        let data={pictureList:result1,}
        res.send({
            code:"200",
            err:"successs",
            data,
            totals,              
        })
     })();
})

//获取每个用户的评论
app.get('/user_comments',(req,res)=>{
  (async function(){
  let user_id=req.query.user_id; 
  let sql="SELECT * FROM `comment`  LEFT JOIN `user` on `comment`.user_id=user.id WHERE user_id ="+user_id
  let result = await handleDB(res,"news","sql","数据库查询出错",sql)
  res.send({code:"200",err:"successs",data:result})
 })();
})  


  //上传图片接口
  app.post('/upload_img',upload.single("picture"),(req,res)=>{ 
    (async function(){
        fs.readFile(req.file.path,(err,data)=>{
            if(err){return res.send('上传失败')}  
  
     //声明图片名字为时间戳和随机数拼接成的，尽量确保唯一性
     let time=Date.now()+parseInt(Math.random()*999)+parseInt(Math.random()*2222);
        
        let keepname=time+req.file.originalname

   // 三个参数 1.图片的绝对路 //2.写入的内容 //3.回调函数  
      fs.writeFile(path.join(__dirname,'public/news/upload/image/'+keepname),data,(err)=>{
        if(err){return res.send('写入失败')}
       
        //上传图片到七牛        
        var config = new qiniu.conf.Config();
        // 空间对应的机房
        config.zone = qiniu.zone.Zone_z2;
    
        var accessKey = 'YrWoZQy06LAH549DlQuYWP4vVIz23oNr3SkFipJh';
        var secretKey = 'BsomB-qe8tVC8i54FBQVyA2-l6nRpK-4RZYldmbO';
        const bucket = "laona1999"
        var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
        var options = {
            scope: bucket,
          };
          var putPolicy = new qiniu.rs.PutPolicy(options);
          var uploadToken=putPolicy.uploadToken(mac);
        
      
        var localFile = localfile.localfile+keepname;
        
        var formUploader = new qiniu.form_up.FormUploader(config);
        var putExtra = new qiniu.form_up.PutExtra();
        var key='news/image/'+keepname;
        // 文件上传
        formUploader.putFile(uploadToken, key, localFile, putExtra, function(respErr,
          respBody, respInfo) {
          if (respErr) {
            throw respErr;
          }
          if (respInfo.statusCode == 200) {
            console.log(respBody.key);
            res.send({err:0,msg:'上传ok',data:"http://qt8o4ylrm.hn-bkt.clouddn.com/"+respBody.key})
          } else {
            console.log(respInfo.statusCode);
            console.log(respBody);
          }
        });
    }) 
    
    
 })
    console.log(req.file);//获取本次上传图片的一些信息
})();
  }) 

app.listen(3000,()=>{
    console.log("Express web server is listen at 3000 port!");    
})
